package com.code.wflow.controller;

import com.alibaba.fastjson2.JSON;
import com.code.wflow.bo.AssignedUserBO;
import com.code.wflow.bo.SelfSelectNode;
import com.code.wflow.common.Constants;
import com.code.wflow.common.RequestContextHolder;
import com.code.wflow.constants.*;
import com.code.wflow.model.*;
import com.code.wflow.node.NodeProperties;
import com.code.wflow.node.SupportSelfSelectNodeProperties;
import com.code.wflow.service.*;
import com.code.wflow.utils.BeanCopierUtils;
import com.code.wflow.utils.InstanceUtils;
import com.code.wflow.wrapper.Result;
import com.code.wflow.wrapper.request.InstanceIdRequest;
import com.code.wflow.wrapper.request.StartInstanceRequest;
import com.code.wflow.wrapper.response.InstanceDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 流程相关
 *
 * @author ggh
 * @date 2022/10/26
 */
@RequestMapping(value = "/instance")
@RestController
public class InstanceController {

    @Autowired
    private WorkflowService workflowService;

    @Autowired
    private WorkflowNodeService workflowNodeService;

    @Autowired
    private InstanceService instanceService;

    @Autowired
    private InstanceNodeService instanceNodeService;

    @Autowired
    private InstanceNodeDetailService instanceNodeDetailService;

    @Autowired
    private WorkflowTaskService taskService;

    /**
     * 启动流程
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/start")
    public Result<String> start(@RequestBody StartInstanceRequest request) {
        if (request == null || request.getWorkflowId() == null || StringUtils.isEmpty(request.getFormData())) {
            return Result.failure(ResultCode.PARAM_LACK);
        }
        try {
            Workflow workflow = workflowService.queryById(request.getWorkflowId());
            if (workflow == null || WorkflowStatus.DISABLE.getVal().equals(workflow.getStatus())) {
                return Result.failure(ResultCode.WORKFLOW_NOT_EXIST);
            }

            Instance instance = BeanCopierUtils.copy(request, Instance.class);
            instance.setStage(InstanceStage.NOT_STARTED.getVal());
            instance.setCreateUserId(RequestContextHolder.getContext().getUserId());

            List<WorkflowNode> nodeList = workflowNodeService.queryByWorkflowId(request.getWorkflowId());
            Map<String, SelfSelectNode> selfSelectNodeMap = null;
            if (!CollectionUtils.isEmpty(request.getSelfSelectNodes())) {
                selfSelectNodeMap = request.getSelfSelectNodes().stream().collect(Collectors.toMap(SelfSelectNode::getId, Function.identity()));
            }
            List<InstanceNode> instanceNodeList = new ArrayList<>(nodeList.size());
            List<InstanceNodeDetail> instanceNodeDetailList = new ArrayList<>(nodeList.size());

            //筛选出除条件节点外需要发起人自选的节点
            List<WorkflowNode> suitNodeList = nodeList.stream()
                    .filter((node) -> Constants.NULL_CONDITION_LEVEL.equals(node.getConditionsLevel())).
                            collect(Collectors.toList());

            // 读取流程定义中每个节点并根据分配人信息存储所有实例节点的信息
            for (WorkflowNode node : suitNodeList) {
                InstanceNode instanceNode = new InstanceNode();
                instanceNode.setWorkflowId(request.getWorkflowId());
                instanceNode.setWorkflowNodeId(node.getId());
                instanceNode.setStage(InstanceNodeStage.NOT_STARTED.getVal());
                instanceNode.setLevel(node.getLevel());
                instanceNodeList.add(instanceNode);

                ResultCode resultCode = handlerAssignedUser(node, request.getWorkflowId(), selfSelectNodeMap, instanceNodeDetailList);
                if (resultCode != null) {
                    return Result.failure(resultCode);
                }
            }

            if (instanceService.start(instance, instanceNodeList, instanceNodeDetailList)) {
                return Result.ok("发起流程成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.failure(ResultCode.INSTANCE_START_ERROR);
    }

    /**
     * 查询实例详情
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryInstanceDetail")
    public Result<InstanceDetailVO> queryInstanceDetail(@RequestBody InstanceIdRequest request) {
        if (request == null || request.getInstanceId() == null) {
            return Result.failure(ResultCode.PARAM_LACK);
        }
        try {
            // 检查流程与实例是否存在
            Instance instance = instanceService.queryDetailById(request.getInstanceId());
            if (instance == null) {
                return Result.failure(ResultCode.INSTANCE_NOT_EXIST);
            }

            InstanceDetailVO response = BeanCopierUtils.copy(instance, InstanceDetailVO.class);

            List<InstanceNode> instanceNodeList = instanceNodeService.queryInstanceNode(instance.getId());
            List<InstanceNodeDetail> detailList = instanceNodeDetailService.queryByInstanceId(instance.getId());
            List<WorkflowNode> nodeList = workflowNodeService.queryByWorkflowId(instance.getWorkflowId());
            Map<Long, WorkflowNode> nodeMap = nodeList.stream().collect(Collectors.toMap(WorkflowNode::getId, Function.identity()));
            Map<Long, List<InstanceNodeDetail>> detailMap = detailList.stream().collect(Collectors.groupingBy(InstanceNodeDetail::getInstanceNodeId));

            response.setInstanceDef(InstanceUtils.buildWorkflowInstance(instanceNodeList, nodeMap, detailMap));

            return Result.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.failure(ResultCode.INSTANCE_DETAIL_QUERY_ERROR);
    }

    /**
     * 撤销流程
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/revoke")
    public Result<String> revoke(@RequestBody InstanceIdRequest request) {
        if (request == null || request.getInstanceId() == null) {
            return Result.failure(ResultCode.PARAM_LACK);
        }
        try {
            // 检查流程与实例是否存在
            Instance instance = instanceService.queryDetailById(request.getInstanceId());
            if (instance == null) {
                return Result.failure(ResultCode.INSTANCE_NOT_EXIST);
            }

            if (InstanceStage.END.getVal().equals(instance.getStage()) || InstanceStage.NOT_STARTED.getVal().equals(instance.getStage())) {
                return Result.failure(ResultCode.INSTANCE_NOT_START_OR_END);
            }

            List<Byte> statusList = Arrays.asList(TaskStatusEnum.TODO.getVal(), TaskStatusEnum.UNREAD.getVal());
            List<WorkflowTask> taskList = taskService.queryByInstanceId(instance.getId(), statusList, TaskFinishEnum.FALSE.isFinish());
            List<Long> taskIdList = taskList.stream().map(WorkflowTask::getId).collect(Collectors.toList());

            boolean result = instanceService.revokeInstance(instance, taskIdList);
            if (result) {
                return Result.ok("申请撤销成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.failure(ResultCode.INSTANCE_REVOKE_ERROR);
    }

    private ResultCode handlerAssignedUser(WorkflowNode node, Long workflowId, Map<String, SelfSelectNode> selfSelectNodeMap, List<InstanceNodeDetail> instanceNodeDetailList) {
        if (NodeTypeEnum.APPROVAL.getType().equals(node.getType()) || NodeTypeEnum.CC.getType().equals(node.getType())) {
            NodeProperties props = JSON.parseObject(node.getProps(), NodeTypeEnum.parse(node.getType()).getCls());
            SupportSelfSelectNodeProperties selfSelectNodeProperties = (SupportSelfSelectNodeProperties) props;

            // 判断发起人自选的条件是否都满足
            SelfSelectNode selfSelectNode = null;
            if (AssignedTypeEnum.SELF_SELECT.getType().equals(selfSelectNodeProperties.assignedType())) {
                // 发起人自选类型
                if (selfSelectNodeMap == null
                        || (selfSelectNode = selfSelectNodeMap.get(node.getCode())) == null || CollectionUtils.isEmpty(selfSelectNode.getAssignedUser())) {
                    return ResultCode.NODE_NOT_ASSIGNED_USER;
                }

                for (AssignedUserBO assignedUser : selfSelectNode.getAssignedUser()) {
                    InstanceNodeDetail instanceNodeDetail = new InstanceNodeDetail();
                    instanceNodeDetail.setWorkflowId(workflowId);
                    instanceNodeDetail.setWorkflowNodeId(node.getId());
                    instanceNodeDetail.setExecutorId(assignedUser.getId());
                    instanceNodeDetail.setExecutorName(assignedUser.getName());
                    instanceNodeDetail.setStatus(HandleTaskStatusEnum.NO_EXECUTE.getType());
                    instanceNodeDetailList.add(instanceNodeDetail);
                }
            } else if (AssignedTypeEnum.ASSIGN_USER.getType().equals(selfSelectNodeProperties.assignedType())) {
                // 指定用户类型
                for (AssignedUserBO assignedUser : selfSelectNodeProperties.assignedUser()) {
                    InstanceNodeDetail instanceNodeDetail = new InstanceNodeDetail();
                    instanceNodeDetail.setWorkflowId(workflowId);
                    instanceNodeDetail.setWorkflowNodeId(node.getId());
                    instanceNodeDetail.setExecutorId(assignedUser.getId());
                    instanceNodeDetail.setStatus(HandleTaskStatusEnum.NO_EXECUTE.getType());
                    instanceNodeDetailList.add(instanceNodeDetail);
                }
            } else {
                return ResultCode.NODE_TYPE_ERROR;
            }
        }
        return null;
    }
}
